<?php
/**
 * Created by PhpStorm.
 * User: davin
 * Date: 14-10-19
 * Time: 下午9:25
 */


class BackRoleService extends ServiceBase {


    public function getList(){
        //允许排序的字段名称数组
        $canOrderCols = array('name', 'display_name', 'created_at');

        $order = Input::get( 'order' );
        $reverse = Input::get( 'reverse',0 );
        $page = Input::get( 'page', 1 );

        $entries = Role::orderby(in_array($order, $canOrderCols)?$order:'created_at', $reverse == 0?'desc':'asc');

        $entries = $entries->paginate(Config::get('app.pagenate_num'))
            ->addQuery('order',$order)
            ->addQuery('reverse',$reverse);

        $links = array(
            "order"=>$order,
            "reverse"=>$reverse,
            "page"=>$page,
        );

        return array('entries'=>$entries, 'links'=>$links);

    }

    public function createRole(){
        $role = new Role();
        $this->parseInput($role,'name');
        $this->parseInput($role,'display_name');

        if(!$role->save()){
            $this->errors()->merge($role->errors());
            return false;
        }
        //relate permission and role
        if($role->savePermissions(Permission::preparePermissionsForSave(Input::get('permissions')))){
            $role->save();
        }

        if (!$role->id) {
            $this->errors()->merge($role->errors());
            return false;
        }

        return true;
    }

    public function updateRole($role){

        $this->parseInput($role,'name');
        $this->parseInput($role,'display_name');

        if(!$role->save()){
            $this->errors()->merge($role->errors());
            return false;
        }
        //relate permission and role
        if($role->savePermissions(Permission::preparePermissionsForSave(Input::get('permissions')))){
            $role->save();
        }

        if (!$role->id) {
            $this->errors()->merge($role->errors());
            return false;
        }

        return true;
    }

    public function deleteRole($role){
        if(!$role->delete()){
            $this->errors()->merge($role->errors());
            return false;
        }
        return true;
    }


}

